package com.service.impl;

import com.entity.Emp;
import com.mapper.MenuMapper;
import com.service.IMenuService;
import com.vo.TreeNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements IMenuService {
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private HttpSession session;

    @Override
    public List<TreeNode> listTreeNodeByEmpId() {
        Emp emp=(Emp)session.getAttribute("empInfo");
        //System.out.println("11111111111111111111111111111111111111");
        System.out.println(session.getAttribute("empInfo"));
        List<TreeNode> treeNodeList=menuMapper.listTreeNodeByEmpId(emp.getEmpId());
        List<TreeNode> returnTreeNodeList=new ArrayList<>();
        for(TreeNode treeNode:treeNodeList){
            if(treeNode.getParentId()==0){
                returnTreeNodeList.add(treeNode);
                bindChild(treeNode,treeNodeList);
            }
        }
        return returnTreeNodeList;
    }

    @Override
    public List<TreeNode> listTreeNodeData() {
        List<TreeNode> treeNodeList=menuMapper.listTreeNodeData();
        List<TreeNode> returnTreeNodeList=new ArrayList<>();
        for(TreeNode treeNode:treeNodeList){
            if(treeNode.getParentId()==0){
                returnTreeNodeList.add(treeNode);
                bindChild(treeNode,treeNodeList);
            }
        }
        return returnTreeNodeList;
    }

    private void bindChild(TreeNode currentNode,List<TreeNode> treeNodeList){
        for(TreeNode treeNode:treeNodeList){
            if(treeNode.getParentId()==currentNode.getId()){
                List<TreeNode> children=currentNode.getChildren();
                if(children==null){
                    children=new ArrayList<>();
                }
                children.add(treeNode);
                currentNode.setChildren(children);
                bindChild(treeNode,treeNodeList);
            }
        }
    }

    @Override
    public int insert(TreeNode treeNode) {
        return menuMapper.insert(treeNode);
    }

    @Override
    public int update(TreeNode treeNode) {
        return menuMapper.update(treeNode);
    }

    @Override
    public int delete(Integer menuId) {
        return menuMapper.delete(menuId);
    }
}
